import DialogStore from ".";
import { observable, action, computed, toJS } from "mobx";
import { Button, message } from 'antd';
import { each } from 'lodash';
import { WeaLocaleProvider } from "ecCom";
import API from '../../apis/cuspath';
import { get } from "https";
import CombineSetDialog from "../../components/dialog/combineSetDialog";
const getLabel = WeaLocaleProvider.getLabel;

export default class BeforeNodeOperateDialogStore extends DialogStore {

    @observable nodeid;
    @observable loading;
    @observable tableDatas = [];
    @observable pathStore;
    @observable readonly = false;
    @observable cells = [];
    @observable fieldsOption;
    @observable allFields = [];
    @observable allFieldsMap = {}; // 所以字段的键值对 方便查找不需在遍历
    @observable lastDatas = {};
    @observable selectedDatas = [];

    constructor(pathStore) {
        super();
        // this.title = getLabel('510981','节点操作菜单设置')
        this.style = { width: 800, height: 500 };
        this.pathStore = pathStore;
        this.hasScroll = true;
        message.config({ top: 60 });
    }

    @computed get canSelectFields() {
        // 已选择的设置为只读
        this.allFields.forEach(f => {
            if(this.selectedDatas.indexOf(f.key) > -1) {
                f.disabled = true;
            } else {
                f.disabled = false;
            }
        });
        const types = this.allFields;

        return types;
    }

    @action open = (params) => {
        this.params = {};
        each(params, (value, key) => {
            if (value) {
                this.params[key] = value;
            }
        });
        this.readonly = this.pathStore.readonly
        this.title = getLabel('513394','节点前附加操作');
        this.buttons = this.getButtons();
        this.nodeid = this.params.nodeid;
        this.appid = this.params.appid;
        this.visible = true;
        this.loading = true;
        API.getBeforeNodeOperateDefault(this.params).then(result => {
            this.loading = false;
            this.allFields = result.allField;
            this.tableDatas = result.defaultValues.map(value => ({
                id:value.id, fieldname:value.fieldname, "defaultValue": value.defaultvalue, "defaultValuespan":value.defaultvaluespan}));
            
            this.allFieldsMap = {};
            this.allFields.forEach(field => {
                this.allFieldsMap[field.key] = field;
            });
            this.cells =[];
            this.handleDefaultValueType(this.tableDatas, "init");
        });
    }

    @action save = () => {
        if(!this.doCheck())
            return;
        this.loading = true;
        API.setBeforeNodeOperateDefault({ appid: this.appid, nodeid: this.nodeid, defaultValues: JSON.stringify(this.tableDatas) }).then(() => {
            this.loading = false;
            message.success(getLabel('502231', '保存成功'));
            this.hide();
        })
    }

    @action setTableDatas = (datas) => {
        // this.cells = [//提交按钮的设置禁用
        //     {
        //         id: '0',
        //         isUsed: {
        //             com: [
        //                 {
        //                     type: "CHECKBOX",
        //                     key: "isUsed",
        //                     disabled: true
        //                 }
        //             ]
        //         },
        //         isUsed: {
        //             com: [
        //                 {
        //                     type: "select",
        //                     key: "btnName",
        //                     disabled: true
        //                 }
        //             ]
        //         }

        //     },
        //     {
        //         id: '1',
        //         isUsed: {
        //             com: [
        //                 {
        //                     type: "browser",
        //                     key: "isUsed",
        //                     disabled: false,
        //                     style: { width: 220 }
        //                 }
        //             ]
        //         }
        //     },
        //     {
        //         id: '12',
        //         isUsed: {
        //             com: [
        //                 {
        //                     type: "INPUT",
        //                     key: "isUsed",
        //                     disabled: false,
        //                     style: { width: 220 }
        //                 }
        //             ]
        //         }
        //     }
        // ];
        this.handleDefaultValueType(datas);
        this.tableDatas = datas;
    }


    // 过滤出变化的行，根据变化给后面的框附上属性
    @action handleDefaultValueType = (datas, isinit) => {
        if(isinit == "init") {
            datas.forEach(d => {
                this.setInputType(d);
            })
        } else {
            const filterData = datas.filter(r => {
                if (!(this.lastDatas[r.id] && this.lastDatas[r.id] == r.fieldname)) {
                    r.defaultValue = null;
                    r.defaultValuespan = null;
                    return true;
                } else {
                    return false;
                }
            });
    
            
            this.setInputType(filterData[0]);
        }
        
        // 此处做处理
        this.lastDatas = {};
        this.selectedDatas =[]
        datas.forEach(d => {
            this.lastDatas[d.id] = d.fieldname;
            this.selectedDatas.push(d.fieldname);
        });
    }

    @action setInputType = (data) => {
        const objId = data ? data.id : null;
        if (objId) {
            const deleteObj = [];
            this.cells.forEach((c, index) => {
                if (c.id == objId) {
                    deleteObj.push(index);
                }
            });
            if (deleteObj.length > 0) {
                for (let i = deleteObj.length - 1; i >= 0; i--) {
                    this.cells.splice(deleteObj[i], 1);
                }
            }
            const prop = this.allFieldsMap[data.fieldname];
            if (prop) {
                if (prop.fieldhtmltype == '1') {
                    // 输入框
                    if (prop.type == '1') {
                        this.cells.push(
                            {
                                id: objId,
                                defaultValue: {
                                    com: [
                                        {
                                            type: "INPUT",
                                            key: "defaultValue",
                                            disabled: false,
                                            style: { width: 220 }
                                        }
                                    ]
                                }
                            }
                        )
                        // 文本
                    } else if (prop.type == '2') {
                        this.cells.push(
                            {
                                id: objId,
                                defaultValue: {
                                    com: [
                                        {
                                            type: "INPUTNUMBER",
                                            key: "defaultValue",
                                            disabled: false,
                                            style: { width: 220 }
                                        }
                                    ]
                                }
                            }
                        )
                        // 整数
                    } else if (prop.type == '3') {
                        // 浮点数 -- 暂时用文本
                        this.cells.push(
                            {
                                id: objId,
                                defaultValue: {
                                    com: [
                                        {
                                            type: "INPUT",
                                            key: "defaultValue",
                                            disabled: false,
                                            style: { width: 220 }
                                        }
                                    ]
                                }
                            }
                        )
                    }
                } else if (prop.fieldhtmltype == '3') {

                    // 设置输入框类型
                    if (prop.type == 2) {
                        this.cells.push(
                            {
                                id: objId,
                                defaultValue: {
                                    com: [
                                        {
                                            type: "DATEPICKER",
                                            key: "defaultValue",
                                            disabled: false,
                                            style: { width: 220 }
                                        }
                                    ]
                                }
                            }
                        )
                    } else if (prop.type == 19) {
                        this.cells.push(
                            {
                                id: objId,
                                defaultValue: {
                                    com: [
                                        {
                                            type: "TIMEPICKER",
                                            key: "defaultValue",
                                            disabled: false,
                                            style: { width: 220 }
                                        }
                                    ]
                                }
                            }
                        )
                    } else if (prop.type == 290) {
                        this.cells.push(
                            {
                                id: objId,
                                defaultValue: {
                                    com: [
                                        {
                                            type: "INPUT",
                                            key: "defaultValue",
                                            disabled: false,
                                            style: { width: 220 }
                                        }
                                    ]
                                }
                            }
                        )
                    } else {

                        // 浏览框
                        this.browserSetting(prop)
                        this.cells.push(
                            {
                                id: objId,
                                defaultValue: {
                                    com: [
                                        {
                                            title: this.browserTitile,
                                            hasAdvanceSerach: true,
                                            type: "BROWSER",
                                            key: "defaultValue",
                                            browserConditionParam: { type: prop.type },
                                            disabled: false,
                                            dataParams: this.dataParams,
                                            conditionDataParams: this.dataParams,
                                            destDataParams: this.dataParams,
                                            isMultCheckbox: this.isMultCheckbox,
                                            isSingle: this.isSingle,
                                            ...this.tabs,
                                            style: { width: 220 }
                                        }
                                    ]
                                }
                            }
                        )
                    }


                } else if (prop.fieldhtmltype == '4') {
                    // check框
                    this.cells.push(
                        {
                            id: objId,
                            defaultValue: {
                                com: [
                                    {
                                        type: "CHECKBOX",
                                        key: "defaultValue",
                                        disabled: false,
                                        style: { width: 220 }
                                    }
                                ]
                            }
                        }
                    )
                    if(data.defaultValue === '1') {
                        data.defaultValue = 1;
                    }
                } else if (prop.fieldhtmltype == '5') {
                    //下拉框
                    // check框
                    this.cells.push(
                        {
                            id: objId,
                            defaultValue: {
                                com: [
                                    {
                                        type: "select",
                                        key: "defaultValue",
                                        disabled: false,
                                        style: { width: 220 },
                                        options:prop.options

                                    }
                                ]
                            }
                        }
                    )
                }
            }
        }
    }

    @action getButtons = () => {
        const buttons = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@jp7dec@cancel`} key="cancel" type="primary" onClick={this.hide}>{getLabel(31129, '取消')}</Button>]
        if (!this.readonly) buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@40zitx@save`} key="save" type="primary" onClick={this.save}>{getLabel(30986, '保存')}</Button>);
        return buttons;
    }

    @action
    browserSetting = (prop) => {
        // const range = this.sheet.getCell(this.row, this.col);
        const btype = (prop.fielddbtype).split(".");
        this.type = btype[btype.length-1];
        this.browserType = prop.type;
        this.browserTitile = prop.title;
        // if (this.type.length == 2) {

        //     this.browserTitile = this.type[1].valueSpan;
        // } else {
        //     if (this.type[1]["valueObj"]) {
        //         this.browserTitile = this.type[1]["valueObj"][0].name;
        //     } else {
        //         this.browserTitile = this.type[1].valueSpan;
        //     }

        // }
        // // 设置输入框类型
        // if (this.browserType == 2) {
        //     this.columns = [{
        //         com: [
        //             { type: 'DATEPICKER', key: 'selectName' }
        //         ],
        //         dataIndex: 'selectName',
        //         title: getLabel('502867', '可选项文字'),
        //         width: '70%',
        //     }]
        // } else if (this.browserType == 19) {
        //     this.columns = [{
        //         com: [
        //             { type: 'TIMEPICKER', key: 'selectName' }
        //         ],
        //         dataIndex: 'selectName',
        //         title: getLabel('502867', '可选项文字'),
        //         width: '70%',
        //     }]
        // } else if (this.browserType == 290){
        //     this.columns = [{
        //         com: [
        //             { type: this.inputType, key: 'selectName' }
        //         ],
        //         dataIndex: 'selectName',
        //         title: getLabel('520405','固定解析维护'),
        //         width: '70%',

        //     }]
        // }else {
        //     this.columns = [{
        //         com: [
        //             { type: this.inputType, key: 'selectName', readonly: 'readonly' }
        //         ],
        //         dataIndex: 'selectName',
        //         title: getLabel('520405','固定解析维护'),
        //         width: '70%',

        //     }]
        // }

        // 由于单选都需要多选，所以需要进行类型转换
        // if (this.browserType == 1)
        //     this.browserType = 17;
        // if (this.browserType == 4)
        //     this.browserType = 57;
        // if (this.browserType == 7)
        //     this.browserType = 18;
        // if (this.browserType == 8)
        //     this.browserType = 135;
        // if (this.browserType == 9)
        //     this.browserType = 37;
        // if (this.browserType == 87)
        //     this.browserType = 184;
        // if (this.browserType == 161)
        //     this.browserType = 162;
        // if (this.browserType == 164)
        //     this.browserType = 194;
        // if (this.browserType == 165)
        //     this.browserType = 166;
        // if (this.browserType == 167)
        //     this.browserType = 168;
        // if (this.browserType == 169)
        //     this.browserType = 170;
        // if (this.browserType == 256)
        //     this.browserType = 257;
        if (["17", "18", "37", "57", "65", "135", "142", "152", "162", "166", "168", "170", "171", "184", "194", "257", "261", "268", "269", "278", "293", "314", "315"].indexOf(this.browserType) > -1) {
            this.isSingle = false;
        } else {
            this.isSingle = true;
        }
        if (this.browserType == '161' || this.browserType == '162') {
            this.dataParams = { ...this.dataParams, type: this.type }
        }else if( this.browserType == '256' || this.browserType == '257') {
            this.dataParams = { ...this.dataParams, cube_treeid: this.type }
        } else if(this.browserType == '171'){
            this.dataParams = {...this.dataParams, status:2};
        } else {
            this.dataParams = {};
        }

        if (this.browserType == '58' || this.browserType == '25' || this.browserType == '13' || this.browserType == '63' || this.browserType == '263' || this.browserType == '34') {
            this.isMultCheckbox = true;
        } else {
            this.isMultCheckbox = false;
        }
        if (this.browserType == '4' || this.browserType == '57' || this.browserType == '167' || this.browserType == '168') {
            this.tabs = {
                tabs: [{
                    "key": "2",
                    "name": getLabel('505968', '组织结构'),
                    "dataURL": null,
                    "dataParams": null,
                    "isSearch": false,
                    "showOrder": 0,
                    "selected": false
                }, {
                    "key": "1",
                    "name": getLabel('505969', '按列表'),
                    "dataURL": null,
                    "dataParams": {
                        "list": "1"
                    },
                    "isSearch": true,
                    "showOrder": 0,
                    "selected": false
                }]
            };
        } else if (this.browserType == '164' || this.browserType == '169' || this.browserType == '170' || this.browserType == '194') {
            this.tabs = {
                tabs: [{
                    "key": "2",
                    "name": getLabel('505968', '组织结构'),
                    "dataURL": null,
                    "dataParams": null,
                    "isSearch": false,
                    "showOrder": 0,
                    "selected": false
                }, {
                    "key": "1",
                    "name": getLabel('505969', '按列表'),
                    "dataURL": null,
                    "dataParams": {
                        "list": "1"
                    },
                    "isSearch": true,
                    "showOrder": 0,
                    "selected": false
                }]
            };
        } else if (this.browserType === '142') {
            this.tabs = {
                tabs: [{
                    "dataParams": { "cmd": "List" },
                    "isSearch": true,
                    "key": "1",
                    "name": "列表",
                    selected: false,
                    showOrder: 0
                },
                {
                    "dataParams": { cmd: "Organization" },
                    "isSearch": false,
                    "key": "2",
                    "name": "组织结构",
                    "selected": false,
                    "showOrder": 0
                },
                {
                    "dataParams": { "cmd": "PublicGroup" },
                    "isSearch": false,
                    "key": "3",
                    "name": "公共组",
                    "selected": false,
                    "showOrder": 0
                },
                {
                    "dataParams": { "cmd": "PrivateGroup" },
                    "isSearch": false,
                    "key": "4",
                    "name": "私人组",
                    "selected": false,
                    "showOrder": 0
                },
                {
                    "dataParams": { "companyType": "1", "cmd": "ExternalUnit" },
                    "isSearch": false,
                    "key": "5",
                    "name": "外部单位",
                    "selected": false,
                    "showOrder": 0
                }]
            };
        } else {
            this.tabs = {};
        }
    }

    @action doCheck = () => {
        const size = this.tableDatas.length;
        const count = this.tableDatas.filter( r => r.fieldname).length;
        if(size >count) {
            message.error(getLabel('512009','可选项文字不能为空!'));
            return false;
        } else {
            return true;
        }
    }

    @action
    willAddDatas = (datas) => {
        setTimeout(() => {
            $('.beforenodeoperate-ant-table-body .ant-table-body').scrollTop($('.beforenodeoperate-ant-table-body .ant-table-body')[0].scrollHeight);
        }, 50);
        return datas;
    };
}
